//---------------------------------------------------------------------------- Strict
'use strict'
//---------------------------------------------------------------------------- Package
const _ = require('lodash')
const OAuth = require('wechat-oauth')
//---------------------------------------------------------------------------- Part
const special = require('../part/special')
const user = require('../part/user')
//---------------------------------------------------------------------------- Object
const client = new OAuth(conf.wechat.appid, conf.wechat.appsecret)
//---------------------------------------------------------------------------- GET
exports.get = {
  //-------------------------------------------------------------------------- enter
  '/enter': async (ctx, next) => {

    // 取参数
    let platform = ctx.query.platform
    let state = ctx.header.referer
    let host = ctx.header.host

    // 跳转
    let redirect = encodeURI('http://' + host + '/return/' + platform)
    ctx.redirect(client.getAuthorizeURL(redirect, state, conf.wechat.scope))
  },
  //-------------------------------------------------------------------------- return
  '/return/:platform': async (ctx, next) => {

    // 取参数
    let platform = ctx.params.platform
    let code = ctx.query.code
    let state = ctx.query.state

    // 进入主逻辑
    try {

      // 获取用户信息
      let result = await user.getUser(client, code)

      // 处理用户信息
      await user.setUser(result, platform, state)
      
      // 正常返回，分两种情况，指定路徑或原路返回。
      // 声明url，并且默认为原路返回
      let url = state

      // 取platform，如果需要跳转到指定页面，则对url进行设置
      let platforms = await special.getSpecial()
      for (let item of platforms) {
        if (item.platform === platform && item.special != '') {
          url = item.special
          break
        }
      }
      
      // 计算参数
      let symbol = '&'
      if (url.indexOf('?') === -1) { symbol = '?' } 

      // 重新修订url，注意：原路返回不要带上state参数
      if (url !== state) {
        url += symbol + 'state=' + encodeURI(state) + '&token_openid=' + result.openid
      } else {
        url += symbol + 'token_openid=' + result.openid
      }

      // 返回
      ctx.redirect(url)
    
    // 错误处理
    } catch (err) {

      // 记录日志
      log.error('错误：' + err)

      // 输出用户提示
      ctx.type = 'application/json; charset=utf-8'
      ctx.body = '微信授权失败，请重新进入<br /><br /><a href="' + state + '">点击重试</a>'
    }
  }
}
